﻿using System;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace Client
{
    class Program
    {
        static byte[] _bufferRec;
        static EndPoint _ep;
        static void Main(string[] args)
        {
            //1) Creo Socket
            Socket udpsck = new Socket(AddressFamily.InterNetwork,SocketType.Dgram, ProtocolType.Udp);
// ReSharper disable InconsistentNaming
            IPEndPoint locEP = new IPEndPoint(IPAddress.Any, 12891);
// ReSharper restore InconsistentNaming
            udpsck.Bind(locEP);

            _ep = new IPEndPoint(IPAddress.Any, 12890);
            _bufferRec = new byte[10];
            udpsck.BeginReceiveFrom(_bufferRec, 0, 10, SocketFlags.None, ref _ep, ReceiveComplete, udpsck);
            
            
            //2) Creo Endpoint destino
// ReSharper disable InconsistentNaming
            IPEndPoint sending_end_point = new IPEndPoint(IPAddress.Parse("239.1.1.1"),12890);
// ReSharper restore InconsistentNaming
            UTF8Encoding enc = new UTF8Encoding();
            byte[] buffer = enc.GetBytes("11111111111222222222");
            
            //3) Envio
            udpsck.SendTo(buffer, SocketFlags.None, sending_end_point);
                udpsck.SendTo(buffer, SocketFlags.None, sending_end_point);

            Console.ReadLine();
         
            
        }

        static void ReceiveComplete(IAsyncResult result)
        {
            Socket socket = result.AsyncState as Socket;
            if (socket != null)
            {
                int bytesReceived = socket.EndReceiveFrom(result, ref _ep);
                UTF8Encoding enc = new UTF8Encoding();
                Console.WriteLine(enc.GetString(_bufferRec, 0, bytesReceived));
                IPEndPoint emp = (IPEndPoint)socket.LocalEndPoint;
                Console.WriteLine(emp.Address);
            }
            Console.WriteLine(_ep.ToString());

        }
    }
}
